package com.shuai.user.service;

import cn.hutool.core.io.FileUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


/**
 * 操作对象存储
 */
@Slf4j
@Service
public class TencentCosService {

    @Value("${tencent.cos.secretId}")
    private String secretId;

    @Value("${tencent.cos.secretKey}")
    private String secretKey;

    @Value("${tencent.cos.bucketName}")
    private String bucketName;


    private COSClient getCOSClient() {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region("ap-nanjing");
        ClientConfig clientConfig = new ClientConfig(region);
        return new COSClient(cred, clientConfig);
    }


    /**
     * 向对象存储上传文件
     */
    public String upload(MultipartFile file) throws IOException {
        COSClient cosClient = getCOSClient();

        InputStream inputStream = file.getInputStream();
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        String key = "sx-ai-station-picture/" + UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        String res = null;
        try {
            cosClient.putObject(bucketName, key, inputStream, objectMetadata);
            res = cosClient.getObjectUrl(bucketName, key).toString();
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
            inputStream.close();
        }
        return res;
    }
}